﻿// -----------------------------------------------------------------------
//  <copyright file="IdentityExtensions.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-15 22:10</last-date>
// -----------------------------------------------------------------------

using System.Security.Claims;

namespace DaprPlus.Extensions;

public static class IdentityExtensions
{
    /// <summary>
    /// 获取用户编号
    /// </summary>
    public static long GetUserId(this ClaimsPrincipal principal)
    {
        return principal is not { Identity.IsAuthenticated: true } ? 0 : principal.Identity.GetUserId();
    }

    /// <summary>
    /// 获取用户编号
    /// </summary>
    public static long GetUserId(this IIdentity identity)
    {
        if (identity is not (ClaimsIdentity { IsAuthenticated: true } claimsIdentity))
        {
            return 0;
        }

        var value = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier)?.Value
            ?? claimsIdentity.FindFirst("sub")?.Value;
        return long.TryParse(value, out var id) ? id : 0;
    }
}